package s0404.dao.mapper;

import s0404.dao.CommonDao;
import s0404.dao.TeacherDao;
import s0404.entity.Department;
import s0404.entity.Teacher;
import s0404.exception.BaseException;
import s0404.factory.DaoFactory;
import s0404.factory.ServiceFactory;
import s0404.service.DepartmentService;
import s0404.util.Condition;
import s0404.util.JdbcHelper;
import s0404.util.Pagination;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * @author 刘永渠
 * @project xg22
 * @date 2024/3/26
 */
public class TeacherDaoImpl implements TeacherDao {

    @Override
    public Collection<Teacher> findAll(
            Connection connection, List<Condition> conditionList,
            Pagination pagination) throws SQLException, BaseException, InvocationTargetException {
        //创建Teacher类型集合类对象，HashSet不保证结果中元素的顺序
        Collection<Teacher> desiredTeachers = new HashSet<Teacher>();
        //创建查询教师的主语句
        StringBuilder sql_select = new StringBuilder("SELECT * FROM bysj.teacher ");
        //如果有条件，则生成条件子句，并附加到主语句后面
        if (conditionList != null) {
            String whereClause = Condition.toWhereClause(conditionList);
            sql_select.append(whereClause);
        }
        //获取Teacher中的元组总数
        int totalNum = DaoFactory.getDao(CommonDao.class,"CommonDaoImpl").count(connection, "Teacher", conditionList);

        String paginationClause = pagination.toLimitClause(totalNum);
        sql_select.append(paginationClause);

        //获得查询教师的语句对象
        PreparedStatement pstmt_select = connection.prepareStatement(sql_select.toString());
        //获得教师对象的结果集
        ResultSet resultSet_select = pstmt_select.executeQuery();
        //遍历结果集，根据每个元素创建对象，并添加到集合类对象desiredTeachers中
        while(resultSet_select.next()) {
            int id = resultSet_select.getInt("id");
            String name = resultSet_select.getString("name");
            int departmentId = resultSet_select.getInt("department_id");
            Department department = ServiceFactory.
                    getService(DepartmentService.class,"DepartmentServiceImpl").
                    find(departmentId);
            Teacher desiredTeacher = new Teacher(id, name, department);
            desiredTeachers.add(desiredTeacher);
        }
        //关闭ResultSet, statement资源
        JdbcHelper.close(resultSet_select, pstmt_select);
        return desiredTeachers;
    }

}
